def last_remaining(n, m):

    if n < 1 or m < 1:
        return -1
    nums = list(range(n))
    idx = 0
    while len(nums) > 1:
        idx = (idx + m - 1) % len(nums)
        del nums[idx]
    return nums[0]

print(last_remaining(7,4))
print(last_remaining(12,5))

